<template>
  <div class="worker-profile">
    <div class="profile-header">
      <div class="avatar-container">
        <el-avatar :size="100" :src="avatarUrl" @error="handleAvatarError">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
        </el-avatar>
        <div class="upload-btn">
          <el-upload
            class="avatar-uploader"
            action="/api/workerProfile/uploadAvatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </div>
      <div class="worker-info">
        <h2>{{ workerInfo.nickname || workerInfo.workerName || '维修工' }}</h2>
        <p class="skill-level">{{ getSkillLevelName(profile.skillLevel) }}</p>
        <p class="signature">{{ profile.signature || '专业维修，用心服务' }}</p>
      </div>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本资料" name="basic">
        <el-form :model="profile" ref="profileForm" label-width="100px" :rules="rules">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profile.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profile.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="个性签名" prop="signature">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="写一句话介绍自己"
              v-model="profile.signature">
            </el-input>
          </el-form-item>
          
          <el-form-item label="工作年限" prop="workYears">
            <el-input-number v-model="profile.workYears" :min="0" :max="50"></el-input-number>
          </el-form-item>
          
          <el-form-item label="技能等级" prop="skillLevel">
            <el-select v-model="profile.skillLevel" placeholder="请选择技能等级">
              <el-option
                v-for="level in skillLevels"
                :key="level.level"
                :label="level.name"
                :value="level.level">
                <span>{{ level.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ level.description }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="专长领域" prop="specializations">
            <el-select
              v-model="selectedSpecializations"
              multiple
              filterable
              placeholder="请选择专长领域">
              <el-option
                v-for="item in specializationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="工作地点偏好" prop="locationPreference">
            <el-input v-model="profile.locationPreference" placeholder="请输入工作地点偏好"></el-input>
          </el-form-item>
          
          <el-form-item label="证书与资质" prop="certifications">
            <div class="cert-list">
              <div 
                v-for="(cert, index) in certifications" 
                :key="index" 
                class="cert-item">
                <el-input v-model="cert.name" placeholder="证书名称"></el-input>
                <el-date-picker
                  v-model="cert.date"
                  type="date"
                  placeholder="获取日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD">
                </el-date-picker>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  circle 
                  @click="removeCertification(index)">
                </el-button>
              </div>
              <el-button type="primary" icon="el-icon-plus" @click="addCertification">添加证书</el-button>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <el-tab-pane label="维修历史" name="repairs">
        <div class="empty-data" v-if="!repairRecords.length">
          <el-empty description="暂无维修记录"></el-empty>
        </div>
        <div v-else>
          <el-table
            :data="repairRecords"
            style="width: 100%">
            <el-table-column
              prop="orderId"
              label="订单号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="repairType"
              label="维修类型">
            </el-table-column>
            <el-table-column
              prop="repairDate"
              label="维修日期"
              width="180">
            </el-table-column>
            <el-table-column
              label="状态">
              <template slot-scope="scope">
                <el-tag :type="getTagType(scope.row.statusCode)">
                  {{ getStatusText(scope.row.statusCode) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button 
                  @click="viewOrderDetail(scope.row)" 
                  type="text" 
                  size="small">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="技能成长" name="skills">
        <div class="skill-growth">
          <el-card class="skill-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>当前技能等级</span>
            </div>
            <div class="skill-progress">
              <el-progress 
                :percentage="getSkillPercentage(profile.skillLevel)" 
                :status="getSkillProgressStatus(profile.skillLevel)">
              </el-progress>
              <div class="level-name">{{ getSkillLevelName(profile.skillLevel) }}</div>
              <div class="level-description">{{ getSkillLevelDescription(profile.skillLevel) }}</div>
            </div>
            
            <div class="skill-tips" v-if="profile.skillLevel < 3">
              <h4>提升技能等级的方法：</h4>
              <ul>
                <li>完成更多的维修订单</li>
                <li>提高客户满意度评分</li>
                <li>获取更多专业证书</li>
                <li>参加系统培训课程</li>
              </ul>
            </div>
            
            <div class="skill-tips" v-else>
              <h4>恭喜您已达到最高技能等级！</h4>
              <p>您可以担任新维修工的导师，分享您的经验和知识。</p>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'WorkerProfile',
  data() {
    return {
      activeTab: 'basic',
      profile: {
        openid: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '',
        skillLevel: 1,
        workYears: 0,
        specializations: '',
        certifications: '',
        locationPreference: '',
      },
      workerInfo: {
        nickname: '',
        workerName: '',
        workerPhone: '',
        workerEmail: '',
      },
      rules: {
        workYears: [
          { type: 'number', required: true, message: '请输入工作年限', trigger: 'blur' }
        ],
        skillLevel: [
          { required: true, message: '请选择技能等级', trigger: 'change' }
        ],
      },
      repairRecords: [],
      avatarUrl: '',
      skillLevels: [],
      specializationOptions: [],
      selectedSpecializations: [],
      certifications: [],
    };
  },
  created() {
    this.getWorkerProfile();
    this.getWorkerInfo();
    this.getRepairRecords();
    this.getSkillLevelInfo();
    this.getSpecializations();
  },
  methods: {
    async getWorkerProfile() {
      try {
        const res = await axios.get('/api/workerProfile/getWorkerProfile');
        if (res.data && res.data.code === 200) {
          this.profile = res.data.data;
          this.avatarUrl = this.profile.avatar || '';
          
          // 处理专长领域JSON
          if (this.profile.specializations) {
            try {
              const specs = JSON.parse(this.profile.specializations);
              this.selectedSpecializations = Array.isArray(specs) ? specs : [];
            } catch (e) {
              console.error('Failed to parse specializations', e);
              this.selectedSpecializations = [];
            }
          }
          
          // 处理证书JSON
          if (this.profile.certifications) {
            try {
              const certs = JSON.parse(this.profile.certifications);
              this.certifications = Array.isArray(certs) ? certs : [];
            } catch (e) {
              console.error('Failed to parse certifications', e);
              this.certifications = [];
            }
          } else {
            this.certifications = [];
          }
        } else {
          this.$message.error('获取个人资料失败');
        }
      } catch (error) {
        console.error('获取个人资料失败', error);
        this.$message.error('获取个人资料失败');
      }
    },
    async getWorkerInfo() {
      try {
        const res = await axios.get('/api/worker/getWorkerInfo');
        if (res.data && res.data.code === 200) {
          this.workerInfo = res.data.data;
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
      }
    },
    async getRepairRecords() {
      try {
        const res = await axios.post('/api/workerHome/queryWorkerOrder', {});
        if (res.data && res.data.code === 200) {
          this.repairRecords = res.data.data.repairOrdersEntities || [];
        }
      } catch (error) {
        console.error('获取维修记录失败', error);
      }
    },
    async getSkillLevelInfo() {
      try {
        const res = await axios.get('/api/workerProfile/getSkillLevelInfo');
        if (res.data && res.data.code === 200) {
          this.skillLevels = res.data.data || [];
        }
      } catch (error) {
        console.error('获取技能等级信息失败', error);
      }
    },
    async getSpecializations() {
      try {
        const res = await axios.get('/api/workerProfile/getSpecializations');
        if (res.data && res.data.code === 200) {
          this.specializationOptions = res.data.data || [];
        }
      } catch (error) {
        console.error('获取专长领域信息失败', error);
      }
    },
    async saveProfile() {
      try {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            // 保存之前处理数据
            const submitProfile = { ...this.profile };
            submitProfile.specializations = this.selectedSpecializations;
            submitProfile.certifications = this.certifications;
            
            const res = await axios.post('/api/workerProfile/updateProfile', submitProfile);
            if (res.data && res.data.code === 200) {
              this.$message.success('个人资料更新成功');
            } else {
              this.$message.error(res.data.msg || '个人资料更新失败');
            }
          } else {
            return false;
          }
        });
      } catch (error) {
        console.error('保存个人资料失败', error);
        this.$message.error('保存个人资料失败');
      }
    },
    resetForm() {
      this.$refs.profileForm.resetFields();
      this.getWorkerProfile();
    },
    getTagType(status) {
      const statusMap = {
        'TO_ACCEPT': 'warning',
        'HAVE_ACCEPTED': 'primary',
        'WAIT_PAY': 'danger',
        'HAVE_PAID': 'primary',
        'WAIT_FINISHED': 'primary',
        'HAVE_FINISHED': 'success',
        'REJECTED': 'info',
      };
      return statusMap[status] || 'info';
    },
    getStatusText(status) {
      const statusMap = {
        'TO_ACCEPT': '待受理',
        'HAVE_ACCEPTED': '已受理',
        'WAIT_PAY': '待支付',
        'HAVE_PAID': '已支付',
        'WAIT_FINISHED': '待完结',
        'HAVE_FINISHED': '已完结',
        'REJECTED': '已驳回',
      };
      return statusMap[status] || '未知状态';
    },
    getSkillLevelName(level) {
      const skillLevel = this.skillLevels.find(item => item.level === level);
      return skillLevel ? skillLevel.name : '未知等级';
    },
    getSkillLevelDescription(level) {
      const skillLevel = this.skillLevels.find(item => item.level === level);
      return skillLevel ? skillLevel.description : '';
    },
    getSkillPercentage(level) {
      const percentageMap = {
        1: 33,
        2: 66,
        3: 100,
      };
      return percentageMap[level] || 0;
    },
    getSkillProgressStatus(level) {
      const statusMap = {
        1: '',
        2: 'warning',
        3: 'success',
      };
      return statusMap[level] || '';
    },
    viewOrderDetail(order) {
      this.$router.push({
        path: '/repairRecord/details',
        query: { orderId: order.orderId }
      });
    },
    addCertification() {
      this.certifications.push({
        name: '',
        date: '',
      });
    },
    removeCertification(index) {
      this.certifications.splice(index, 1);
    },
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.avatarUrl = res.data;
        this.profile.avatar = res.data;
        this.$message.success('头像上传成功');
      } else {
        // 静默处理头像上传失败，不显示错误信息
        console.log('头像上传失败:', res.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/WEBP格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarError() {
      this.avatarUrl = '';
    }
  }
}
</script>

<style scoped>
.worker-profile {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  min-height: 500px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-container {
  margin-right: 30px;
  text-align: center;
}

.upload-btn {
  margin-top: 10px;
}

.worker-info {
  flex-grow: 1;
}

.skill-level {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-top: 5px;
}

.signature {
  color: #606266;
  font-style: italic;
  margin-top: 5px;
}

.el-tabs {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.cert-list {
  border: 1px dashed #ccc;
  padding: 15px;
  border-radius: 4px;
}

.cert-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.cert-item .el-input {
  margin-right: 10px;
}

.cert-item .el-date-picker {
  margin-right: 10px;
}

.skill-card {
  margin-bottom: 20px;
}

.skill-progress {
  padding: 20px 0;
}

.level-name {
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
  color: #409EFF;
}

.level-description {
  color: #606266;
  margin-bottom: 15px;
}

.skill-tips {
  background: #f0f9eb;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.skill-tips h4 {
  color: #67c23a;
  margin-top: 0;
}

.skill-tips ul {
  padding-left: 20px;
  margin-bottom: 0;
}
</style> 